////////////////////////////////////////////////////////////////////////////////
//File:					UglyVertexBuffer.cpp
//Author:				Kesitem
//This file is part of UglyProject.
//See UglyProject.txt for copyright informations.
////////////////////////////////////////////////////////////////////////////////
#include "UglyVertexBuffer.h"
#include "UglyLog.h"
#include "UglyOpenGlError.h"

namespace Ugly
{

/**
 * \brief Constructor.
 */
VertexBuffer::VertexBuffer()
{
    mBufferName = 0;
    mTarget = GL_NONE;
    mUsage = GL_NONE;
}


/**
 * \brief Destructor.
 */
VertexBuffer::~VertexBuffer()
{
    destroy();
}


/**
 * \brief Create vertex buffer.
 *
 * \param   _Target OpenGL target of the buffer(GL_ARRAY_BUFFER, GL_ELEMENT_ARRAY_BUFFER, etc...).
 * \param   _Usage  OpenGL usage of the buffer(GL_STREAM_COPY, GL_STATIC_DRAW, etc...).
 * \return False if error.
 */
bool VertexBuffer::create(GLenum _Target, GLenum _Usage)
{
    //Create buffer name
    glGenBuffers(1, &mBufferName);

    //Bind (and create) the buffer
    mTarget = _Target;
    glBindBuffer(mTarget, mBufferName);
    if(gOpenGlError.check())
    {
        gLog << "Error! VertexBuffer::create: failed to bind buffer.\n";
        gLog << "   OpenGL error: " << gOpenGlError.getErrorDesc() << "\n";
        return false;
    }

    //Save usage hint
    mUsage = _Usage;

    return true;
}


/**
 * \brief Destroy vertex buffer.
 */
void VertexBuffer::destroy()
{
    //Destroy buffer
    glDeleteBuffers(1, &mBufferName);
    mBufferName = 0;
}


/**
 * \brief Set buffer data.
 *
 * \param   _Size   Size in bytes of the data.
 * \param   _Data   Data.
 * \return False if error.
 */
bool VertexBuffer::setData(GLsizeiptr _Size, const GLvoid *_Data)
{
    glBindBuffer(mTarget, mBufferName);
    if(gOpenGlError.check())
    {
        gLog << "Error! VertexBuffer::setData: failed to bind buffer.\n";
        gLog << "   OpenGL error: " << gOpenGlError.getErrorDesc() << "\n";
        return false;
    }

    glBufferData(mTarget, _Size, _Data, mUsage);
    if(gOpenGlError.check())
    {
        gLog << "Error! VertexBuffer::setData: failed to set buffer data.\n";
        gLog << "   OpenGL error: " << gOpenGlError.getErrorDesc() << "\n";
        return false;
    }

    return true;
}


/**
 * \brief Bind the vertex buffer.
 *
 * \return False if error.
 */
bool VertexBuffer::bind()
{
    glBindBuffer(mTarget, mBufferName);
    if(gOpenGlError.check())
    {
        gLog << "Error! VertexBuffer::bind: failed to bind buffer.\n";
        gLog << "   OpenGL error: " << gOpenGlError.getErrorDesc() << "\n";
        return false;
    }

    return true;
}

}//namspace Ugly
